package com.alipay.rebate.shop.scheduler.orderimport;

import com.alipay.rebate.shop.model.CommissionFreezeLevelSettings;
import com.alipay.rebate.shop.model.Orders;
import com.alipay.rebate.shop.model.User;
import java.math.BigDecimal;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;

@Component
public class PaidOrdersImporter extends AbstractOrdersImporter{

  Logger logger = LoggerFactory.getLogger(PaidOrdersImporter.class);

  @Autowired
  DataSourceTransactionManager dataSourceTransactionManager;
  @Autowired
  TransactionDefinition transactionDefinition;

  @Override
  @Transactional
  void doDealWithOrder(Orders orders, Orders previousOrder, Long parentUserId, Long parentPUserId,
      User user, User oneLevelUser) {
    TransactionStatus transactionStatus = dataSourceTransactionManager.getTransaction(transactionDefinition);
    try {
      // 如果先前数据库没有订单，那么用户相应订单数加1
      if(previousOrder == null){
        countUserOrdersNum(orders);
      }
      // 根据状态获取到实际能拿到的所有佣金
      BigDecimal totalGetMoney = getTotalGetMoney(orders);
      logger.debug("Paid totalGetMoney is : {}", totalGetMoney);

      // 如果是活动订单
      dealwithActivityOrdersLogicIfis(previousOrder,orders,user.getUserId());

      // 订单付款状态
      // 计算用户佣金，用户上级佣金，上上级佣金，上上上级佣金
      countCommission(totalGetMoney,orders,parentUserId, parentPUserId,user,oneLevelUser);

      // 如果数据库有记录，那么更新订单信息，没有则直接插入
      saveOrUpdateOrders(orders,previousOrder);

      // 获取冻结配置，根据冻结配置决定是否冻结
      CommissionFreezeLevelSettings freezeCommissionSettings = getFreezeSettingsByMoney(orders.getUserCommission());
      logger.debug("CommissionFreezeLevelSettings is : {}",freezeCommissionSettings);

      // 创建收益记录
      createIncomeRecord(orders, user.getUserId(), parentUserId,
          parentPUserId,previousOrder,freezeCommissionSettings);

      dataSourceTransactionManager.commit(transactionStatus);
    }catch (Exception ex){
      logger.error("paid orders exception is : {}",ex);
      dataSourceTransactionManager.rollback(transactionStatus);
    }
  }

  @Override
  protected void createIncomeRecord(Orders orders, Long userId, Long parentUserId,
      Long parentPuserId, Orders previousOrders,
      CommissionFreezeLevelSettings freezeCommissionSettings) {
    logger.debug("insert userIncome record");
    insertUserIncome(orders,userId,parentUserId,parentPuserId,freezeCommissionSettings);

//    if(previousOrders == null){
//      logger.debug("paid order insert userIncome record");
//      insertUserIncome(orders,userId,parentUserId,parentPuserId,freezeCommissionSettings);
//    }else{
//      // 查询数据库是否已经有用户记录
//      List<UserIncome> userIncomeList = userIncomeMapper
//              .selectUserIncomeByOrdersId(orders.getTradeId());
//      if (userIncomeList.size() > 0) {
//        // 如果数据库有记录，那么就更新住居
//        logger.debug("orders is : {}",orders.getTradeId());
//        logger.debug("paid orders update userIncome record");
//        updateUserIncome(orders, userId, parentUserId, parentPuserId,
//                userIncomeList, orders.getTkStatus(), freezeCommissionSettings);
//      }else{
//        logger.debug("paid order insert userIncome record");
//        insertUserIncome(orders,userId,parentUserId,parentPuserId,freezeCommissionSettings);
//      }
//    }

  }
}
